package tk.djcrazy.instantmessage.serviceImpl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import tk.djcrazy.instantmessage.dao.IDao;
import tk.djcrazy.instantmessage.domain.FriendGroup;
import tk.djcrazy.instantmessage.service.IFriendGroupService;
import tk.djcrazy.instantmessage.service.IUserService;

@Service
public class FriendGroupServiceImpl extends ServiceImpl<FriendGroup> implements
		IFriendGroupService  {
	@Resource
	private IUserService userService;

	@Override
	public void create(FriendGroup baseBean) {
		getDao().create(baseBean);
	} 

	@Override
	public void delete(FriendGroup baseBean) {
		getDao().delete(baseBean);
	}

	@Override
	public void save(FriendGroup friendGroup) {
		getDao().save(friendGroup);
	}
	@Override
	public FriendGroup findById(int id) {
		return getDao().findById(FriendGroup.class, id);
	}
	
	@Override
	public void addFriendGroup(int ownUserId, String groupName) {

		FriendGroup group = new FriendGroup();
		group.setGroupName(groupName);
		group.setOwnUser(userService.findById(ownUserId));
		create(group);
	}
 
	@Override
	public void deleteFriendGroup(int groupId) {
		delete(findById(groupId));
	}

	@Override
	public void addFriendIntoGroup(int groupId, int userId) {

		FriendGroup group = this.findById(groupId);
		group.getContentUsers().add(
				userService.findById(userId));
		this.getDao().save(group);
	}

	@Override
	public void deleteFriendFromGroup(int groupId, int userId) {
		FriendGroup group = this.findById(groupId);
		if (group == null) {
			throw new IllegalArgumentException("groupId does not exist!");
		} else {
			group.getContentUsers().remove(
					userService.findById( userId));
			this.getDao().save(group);
		}
	}

	@Override
	public void moveFriendFromGroupToGroup(int fromGroupId, int toGroupId,
			int userId) {
		deleteFriendFromGroup(fromGroupId, userId);
		addFriendIntoGroup(toGroupId, userId);
	}
	
	@Override
	public void setDao(IDao<FriendGroup> dao) {
		super.setDao(dao);
	}

	public IUserService  getUserService() {
		return userService;
	}

	public void setUserService(IUserService  userService) {
		this.userService = userService;
	}

	
 }
